function [ border ] = detectBorder( vertices, triangles )
nTri = size(triangles, 1);

border = 0;
borderSize = 0;

% iterate over triangles of the mesh
for ti = 1 : nTri
    edges = edgesOfTri(triangles(ti, :));
    for i = 1 : 3
        edge = edges(i,:);
        found = findTriContainingEdge(triangles, edge, ti);
        % if we have not found any other triangle containing the edge (i.e.
        % only one triangle on the mesh shares the edge), it means that it
        % is border edge;
        if( found < 2)
            borderSize = borderSize + 1;
            border(borderSize) = edge(1);
            borderSize = borderSize + 1;
            border(borderSize) = edge(2);
        end % if
    end % for
    
    % Display progress
    if( mod(ti, 50) == 0)
        disp(['Progress: ' int2str(ti) ' triangles processed..']);
    end % if
end % for tri

% Remove duplicates from array of borderline vertices
border = unique(border)';

end % function

% -- --

function [edges] = edgesOfTri(tri)
    edges = zeros(3, 2);
    edges(1,:) = [tri(1), tri(2)];
    edges(2,:) = [tri(2), tri(3)];
    edges(3,:) = [tri(3), tri(1)];
end % function edgesOfTri

% -- --

function [found] = findTriContainingEdge(triangles, edge, ti)
nTri = size(triangles, 1);
% Initialize as we have not found this edge in any other triangle on the
% mesh
found = 0;

for i = 1 : nTri
    % In other case if we found => increse the counter
    if( triangleContainsEdge(triangles(i,:), edge) )
        found = found + 1;
    end % if
    
end % for
end % function findTriContainingEdge

% -- --

function [contains] = triangleContainsEdge(triangle, edge)
    contains = 0;
    edges = edgesOfTri(triangle);
    for i = 1 : 3
        check1 = norm(edges(i,:) - edge);
        check2 = norm(edges(i,:) - fliplr(edge));
        if( (check1==0) || (check2==0) )
            contains = 1;
            return;
        end % if
    end % for
end % function triangleContainsEdge
